const express = require('express')
const logger = require('morgan')
const {StatusCodes } = require('http-status-codes')
// 引入跨域库
const cors = require('cors')
const fs = require('fs-extra')
const path = require('path')
const { reject } = require('core-js/fn/promise')
const app = express()
app.use(logger('dev'))
app.use(cors());
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static(path.resolve(__dirname, 'public')))
const PUNLIC_DIR = path.resolve(__dirname, 'public')
const TEMP_DIR = path.resolve(__dirname,'temp')
// 存放上传并合并好的文件
fs.ensureDirSync(PUNLIC_DIR)
// 存放分片的文件
fs.ensureDirSync(TEMP_DIR)

// 接口i
app.post("/upload/:filename", async (req, res, next) => {
  const { filename } = req.params
  const { chunkFileName } = req.query
  // 创建用户保存此文件的分片的目录
  const chunkDir = path.resolve(TEMP_DIR, filename)
  // 分片的文件路径
  const chunkFilePath = path.resolve(chunkDir, chunkFileName)
  // 先确定分片目录存在
  await fs.ensureDir(chunkDir)
  // 创建此文件的可写流
  const ws = fs.createWriteStream(chunkFilePath, {})
  // 后面会实现暂停操作，如果客户端点击了暂停按钮,会取消上传的操作,取消之后会在服务器触发请求
  // aborted事件关闭可写流
  req.on('aborted', () => {ws.close()})
  // 使用管道的方式把请求中的请求体流数据写入到文件中
  await pipeStream(req,ws)
  res.send({
    msg:'ok'
  })
})
app.get('/merge/:filename', (req, res, next) => {
  res.json({ success: true })
});
function pipeStream(rs, ws) {
  return new Promise((resolve, reject) => {
    // 把可读流中的数据写入可写流中
    rs.pipe(ws).on('finish',resolve).on('error',reject)
  })
}
app.listen(3000, () => {
  console.log('3000服务器启动成功...');
})